package com.ahui.mallchat.common.websocket;

import cn.hutool.core.net.url.UrlBuilder;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpRequest;

import java.net.InetSocketAddress;
import java.util.Optional;

/**
 * Author:ahui
 * Description:
 * Date: 2024/7/20 16:56
 */
public class HttpHeadersHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof FullHttpRequest) {
            HttpRequest request = (HttpRequest) msg;
            UrlBuilder urlBuilder = UrlBuilder.ofHttp(request.getUri());
            Optional<String> tokenOptionalS = Optional.of(urlBuilder)
                    .map(UrlBuilder::getQuery)
                    .map(k -> k.get("token"))
                    .map(CharSequence::toString);
            //如果token存在 保存到 channel 附件
            tokenOptionalS.ifPresent(s -> NettyUtil.setAttr(ctx.channel(), NettyUtil.TOKEN, s));
            //移除后面拼接的所有参数
            request.setUri(urlBuilder.getPath().toString());
            //取用户ip
            String ip = request.headers().get("X-Real-IP");
            if (StringUtils.isBlank(ip)){
                InetSocketAddress address = (InetSocketAddress) ctx.channel().remoteAddress();
                ip = address.getAddress().getHostAddress();
            }
            //保存到 channel 附件
            NettyUtil.setAttr(ctx.channel(),NettyUtil.IP,ip);
            //处理器只需要用一次
            ctx.pipeline().remove(this);

        }
            ctx.fireChannelRead(msg);
    }
    /**
     * FullHttpRequest request = (FullHttpRequest) msg;
     *             UrlBuilder urlBuilder = UrlBuilder.ofHttp(request.uri());
     *
     *             // 获取token参数
     *             String token = Optional.ofNullable(urlBuilder.getQuery()).map(k->k.get("token")).map(CharSequence::toString).orElse("");
     *             NettyUtil.setAttr(ctx.channel(), NettyUtil.TOKEN, token);
     *
     *             // 获取请求路径
     *             request.setUri(urlBuilder.getPath().toString());
     *             HttpHeaders headers = request.headers();
     *             String ip = headers.get("X-Real-IP");
     *             if (StringUtils.isEmpty(ip)) {//如果没经过nginx，就直接获取远端地址
     *                 InetSocketAddress address = (InetSocketAddress) ctx.channel().remoteAddress();
     *                 ip = address.getAddress().getHostAddress();
     *             }
     *             NettyUtil.setAttr(ctx.channel(), NettyUtil.IP, ip);
     *             ctx.pipeline().remove(this);
     *             ctx.fireChannelRead(request);
     */
}
